package net.flowas.jenkins.plugindownload;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.Manifest;

public class WithDependencyDownloader {
	private static final String PLUGIN_BASE_URL = "https://updates.jenkins-ci.org/latest/";
	private static final List<String> downloaded = new ArrayList<>();
	public static void main(String[] args) throws IOException, URISyntaxException {
		String baseDir="";
		if(args.length>0) {
			baseDir = args[0];
			Configs.appentBaseDir(baseDir);
			System.out.println(Configs.getOutDir());
		}
		URI pluginListUri = Thread.currentThread().getContextClassLoader().getResource("pluginList.txt").toURI();
		List<String> pluginNames = Files.readAllLines(Paths.get(pluginListUri));
		MavenCmdDownloader downloader = new MavenCmdDownloader();
		downloader.init();
		for (String pluginDescription : pluginNames) {
			if(pluginDescription.startsWith("#")) {
				continue;
			}else if(pluginDescription.contains(":")) {
				String[] pair = pluginDescription.split(":");
				downLoadPlugin(downloader, pair[0],pair[1]);
			}else {
				System.out.println("plugin description is in wrong format:"+pluginDescription);
			}
        }
		System.out.println("finished");
	}
	private static void downLoadPlugin(MavenCmdDownloader downloader, String pluginName,String pluginVersion)
			throws IOException, URISyntaxException, MalformedURLException {
		
		Artifact artifact = downloader.getArtifact(pluginName);
		if(artifact==null) {
			System.out.println("missing plugin info for "+pluginName+",attempt download by guess");
			artifact = new Artifact();
			artifact.setId(pluginName);
			artifact.setGroup(downloader.getGroup(pluginName));
			artifact.setVersion(pluginVersion);			
		}else {
			System.out.println("downloading "+pluginName);
			if(!artifact.getVersion().equals(pluginVersion)) {
				System.out.println("use version "+artifact.getVersion()+" overrides version "+pluginVersion);
			}
		}	
		
		String pluginFileName = pluginName+".hpi";
		String hpiFile = Configs.getOutDir() + pluginFileName;
		//如果已经下载了，就跳过下载。
		if(!Files.exists(Paths.get(hpiFile))) {
			downloader.executeDownlod(artifact );
		}
		String manifestPath = "jar:file:" + hpiFile+"!/META-INF/MANIFEST.MF";
		Manifest mani = null;
		try (InputStream meniIn = new URL(manifestPath).openStream()){
			mani =new Manifest(meniIn);
		}catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}			
		}
		if(mani==null) {
			InputStream meniIn = new URL(manifestPath).openStream();
			mani =new Manifest(meniIn);
			meniIn.close();
		}
		downloaded.add(pluginName);
		String dependenciesText = mani.getMainAttributes().getValue("Plugin-Dependencies");
		if(dependenciesText!=null) {
			//Plugin-Dependencies: token-macro:1.5.1,naginator:1.16;resolution:=optional
			String[] depencies = dependenciesText.split(",");
			for (String dependency : depencies) {
				String[] properties = dependency.split(";");
				String artifactText = properties[0];
				boolean resolution = true;
				if(properties.length>1) {
					String resolutionText = properties[1];
					String[] resolutionPair = resolutionText.split(":=");
					if("resolution".equals(resolutionPair[0]) && "optional".equals(resolutionPair[1])) {
						resolution = false;
					}
				}
				if(resolution) {
					String[] artifactPair = artifactText.split(":");
					if(downloaded.contains(artifactPair[0])) {
						continue;
					}else {
						downLoadPlugin(downloader,artifactPair[0],artifactPair[1]);
					}
				}
			}
		}
	}
}
